#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "driver/i2c.h"
typedef enum
{
    KEY_0,
    KEY_1,
    KEY_2,
    KEY_3,
    KEY_4,
    KEY_5,
    KEY_6,
    KEY_7,
    KEY_8,
    KEY_9,
    KEY_SHARP,
    KEY_M,
    KEY_NO
} Touch_Key;
static void SC12B_WriteByte(uint8_t reg, uint8_t data)
{
    uint8_t write_data[2] = {reg, data};
    i2c_master_write_to_device(GPIO_NUM_0, 0x42, write_data, sizeof(write_data), 1000);
}
static uint8_t SC12B_ReadByte(uint8_t reg)
{
    uint8_t data = 0;
    i2c_master_write_read_device(GPIO_NUM_0, 0x42, &reg, 1, &data, 1, 1000);
    return data;
}
TaskHandle_t keyTaskHandle;
void SC12B_ISR(void)
{
    xTaskNotifyFromISR(keyTaskHandle, (uint32_t)1, eSetValueWithoutOverwrite, NULL);
}
void SC12B_Init(void)
{
    i2c_config_t i2c_conf = {
        .mode = I2C_MODE_MASTER,
        .sda_io_num = GPIO_NUM_2,
        .sda_pullup_en = GPIO_PULLUP_ENABLE,
        .scl_io_num = GPIO_NUM_1,
        .scl_pullup_en = GPIO_PULLUP_ENABLE,
        .master.clk_speed = 400000};
    i2c_param_config(I2C_NUM_0, &i2c_conf);
    i2c_driver_install(I2C_NUM_0, I2C_MODE_MASTER, 0, 0, 0);
    gpio_config_t gpio_conf = {
        .intr_type = GPIO_INTR_POSEDGE,
        .mode = GPIO_MODE_INPUT,
        .pull_down_en = 1,
        .pull_up_en = 0,
        .pin_bit_mask = (1ULL << GPIO_NUM_0)};
    gpio_config(&gpio_conf);
    gpio_isr_handler_add(GPIO_NUM_0, SC12B_ISR, NULL);
    SC12B_WriteByte(0x00, 0x25);
    SC12B_WriteByte(0x01, 0x25);
}
Touch_Key SC12B_ReadTouchKey(void)
{
    uint16_t data = (SC12B_ReadByte(0x08) << 4) | (SC12B_ReadByte(0x09) >> 4);
    Touch_Key key = KEY_NO;
    switch (data)
    {
    case 1 << 11:
    {
        key = KEY_0;
        break;
    }
    case 1 << 10:
    {
        key = KEY_1;
        break;
    }
    case 1 << 9:
    {
        key = KEY_2;
        break;
    }
    case 1 << 8:
    {
        key = KEY_3;
        break;
    }
    case 1 << 7:
    {
        key = KEY_7;
        break;
    }
    case 1 << 6:
    {
        key = KEY_5;
        break;
    }
    case 1 << 5:
    {
        key = KEY_6;
        break;
    }
    case 1 << 4:
    {
        key = KEY_4;
        break;
    }
    case 1 << 3:
    {
        key = KEY_M;
        break;
    }
    case 1 << 2:
    {
        key = KEY_8;
        break;
    }
    case 1 << 1:
    {
        key = KEY_9;
        break;
    }
    case 1 << 0:
    {
        key = KEY_SHARP;
        break;
    }
    default:
        break;
    }
    return key;
}
void app_main(void)
{
    gpio_install_isr_service(0);
    SC12B_Init();
    keyTaskHandle = xTaskGetCurrentTaskHandle();
    while (1)
    {
        if (ulTaskNotifyTake(pdTRUE, 5000))
        {
            ESP_LOGE("", "key: %d\n", SC12B_ReadTouchKey());
        }
    }
}
